package utils

import (
	"log"
	"reflect"
	"strings"
)

type Query struct {
	TableName string
	Entity    any
}

func ReflectEntity(entity any) {
	typeOf := reflect.TypeOf(entity)
	field := typeOf.Elem()
	for i := 0; i < field.NumField(); i++ {
		name := field.Field(i).Name
		log.Println(name)
		dbName := field.Field(i).Tag.Get("db")
		log.Println("dbName:" + dbName)
	}
}

func ReflectEntityInsert(tableName string, entity any) string {
	var sql strings.Builder
	var params strings.Builder
	params.WriteString("(")
	sql.WriteString("insert into ")
	sql.WriteString("`" + tableName + "`" + " (")
	typeOf := reflect.TypeOf(entity)
	field := typeOf.Elem()
	for i := 0; i < field.NumField(); i++ {
		//name := field.Field(i).Name
		//log.Println("name:" + name)
		dbName := field.Field(i).Tag.Get("db")
		//log.Println("dbName:" + dbName)
		if i == field.NumField()-1 {
			sql.WriteString("`" + dbName + "`" + " ")
			params.WriteString("? ")
		} else {
			sql.WriteString("`" + dbName + "`" + ", ")
			params.WriteString("?, ")
		}
	}
	params.WriteString(")")
	sql.WriteString(") values ")
	sql.WriteString(params.String())
	return sql.String()
}

func ReflectEntityUpdate(tableName string, entity any) string {
	var sql strings.Builder
	sql.WriteString("update ")
	sql.WriteString("`" + tableName + "`" + " set ")
	typeOf := reflect.TypeOf(entity)
	field := typeOf.Elem()
	for i := 0; i < field.NumField(); i++ {
		//name := field.Field(i).Name
		//log.Println("name:" + name)
		dbName := field.Field(i).Tag.Get("db")
		//log.Println("dbName:" + dbName)
		if i == field.NumField()-1 {
			sql.WriteString("`" + dbName + "`" + " = ? ")
		} else {
			sql.WriteString("`" + dbName + "`" + " = ?, ")
		}
	}
	sql.WriteString("where `id` = ? ")
	return sql.String()
}

func Select(tableName string, columns ...string) any {
	var sql strings.Builder
	sql.WriteString("select ")
	for index, columnName := range columns {
		if index == len(columns)-1 {
			sql.WriteString(columnName + " ")
		} else {
			sql.WriteString(columnName + ", ")
		}
	}
	sql.WriteString("from ")
	sql.WriteString(tableName + " ")
	return sql.String()
}
